package com.keyrus.user.service.impl;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.keyrus.user.pojo.KomsResult;
import com.keyrus.user.pojo.User;
import com.keyrus.user.repository.KomsUserRepository;
import com.keyrus.user.service.KomsUserService;

/**
 * @author David
 * @create 2018-10-24 19:48
 */

@Service
public class KomsUserServiceImpl implements KomsUserService
{
    @Autowired
    private KomsUserRepository userRepository;

    /**
     * 根据id找到用户
     * @param id    用户id
     * @return      用户对象
     */
    @Override
    public User getUserById(final String id)
    {
        return userRepository.findUserById(id);
    }

    /**
     * 根据uuid找到用户
     * @param uuid    用户uuid
     * @return      用户对象
     */
    @Override
    public User getUserByUuid(String uuid)
    {
        return userRepository.findUserByUuid(uuid);
    }

    /**
     * 保存用户
     * @param user  用户
     * @return  成功失败
     */
    @Override
    public Boolean saveUser(User user)
    {
        try
        {
            userRepository.save(user);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 清空传入用户的uuid
     * @param user  用户
     * @return  成功失败
     */
    @Override
    public Boolean clearUuid(User user)
    {
        user.setUuid("");
        try
        {
            userRepository.save(user);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据用户名密码生成用户
     * @param id  id
     * @param name  用户名
     * @param password  密码
     * @return  uuid
     */
    @Override
    public KomsResult generateUser(String id, String name, String password)
    {
        final User user = new User(id, name, password, "", new ArrayList<String>(){{add("admin");}});

        try
        {
            userRepository.save(user);
            return new KomsResult(true, "注册成功", user);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return new KomsResult(false, "注册失败", "");
        }
    }
}
